package com.shuoyue.ycgk.ui.account.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.appcatch.SPUtils;
import com.shuoyue.ycgk.base.BaseMvpFragment;
import com.shuoyue.ycgk.entity.UserInfo;
import com.shuoyue.ycgk.ui.account.AccountContract;
import com.shuoyue.ycgk.ui.account.BindPhoneActivity;
import com.shuoyue.ycgk.ui.account.SmsContract;
import com.shuoyue.ycgk.ui.common.CstWebActivity;
import com.shuoyue.ycgk.ui.main.MainTabActivity;
import com.shuoyue.ycgk.utils.DevicesUtil;
import com.shuoyue.ycgk.utils.SimpleCodeUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

public class FragmentSmsLogin extends BaseMvpFragment<AccountContract.Presenter>
        implements AccountContract.View, SmsContract.View {

    @BindView(R.id.phone_num)
    EditText phoneNum;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.getCode)
    TextView getCode;
    @BindView(R.id.checkAgreement)
    CheckBox checkAgreement;
    private TimeCount time;
    SmsContract.Presenter smsPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_smslogin;
    }

    @Override
    protected void initView() {
        time = new TimeCount(60000, 1000);
    }

    @Override
    public void initData() {
        super.initData();
        smsPresenter = new SmsContract.Presenter();
        smsPresenter.attachView(this);
        mPresenter = new AccountContract.Presenter();
        mPresenter.attachView(this);
    }

    @OnClick({R.id.app_deal, R.id.getCode, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.app_deal:
                CstWebActivity.start(mContext,
                        Constant.HOST_INTERFACE
                                + "/api/share/agreement", "用户协议");
                break;
            case R.id.getCode:
                String phone = phoneNum.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    toast("请输入手机号码");
                    return;
                }
                smsPresenter.sendSms(phone);
                break;
            case R.id.submit:
                login();
                break;
        }
    }

    void login() {
        if (!checkAgreement.isChecked()) {
            toast("请阅读并了解用户协议，如果您同意协议，请勾选同意");
            return;
        }
        String phone = phoneNum.getText().toString();
        String sms = editCode.getText().toString();
        String deviceName = null, imei = null;
//        if (EasyPermissions.hasPermissions(mContext,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_EXTERNAL_STORAGE)) {
//            deviceName = DevicesUtil.getManuFacturer() + DevicesUtil.getModel();
////            imei = DevicesUtil.getIMEI(mContext);
//            imei = SimpleCodeUtil.getSimpleDeviceCode(mContext);
//            if (TextUtils.isEmpty(imei)) {
//                UUID uuid = UUID.randomUUID();
//                imei = uuid.toString();
//                SimpleCodeUtil.writeSimpleDeviceCode(mContext, imei);
//            }
//        } else {
//            EasyPermissions.requestPermissions(this, "需要获取存储权限",
//                    109,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE);
//            toast("需要获取存储权限");
//            return;
//        }
        deviceName = DevicesUtil.getManuFacturer() + DevicesUtil.getModel();
        imei = Settings.System.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
        if (TextUtils.isEmpty(imei)) {
            imei = deviceName;
        }
        if (sms.length() == 0) {
            toast("请输入验证码");
            return;
        }
        mPresenter.smslogin(phone, sms, imei, deviceName);
    }

    /**
     * 发送验证码后
     */
    @Override
    public void sendSuc(String phone) {
        toast("验证码发送成功");
        time.start();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        if (time != null) {
            time.cancel();
        }
        super.onDestroyView();
    }


    @Override
    public void loginSuc(UserInfo userInfo) {
        ((LoginActivity) getActivity()).loginSuc(userInfo);

//        if (userInfo != null) {
//            MemeryCatch.token = userInfo.getToken();
//            SPUtils.updateUserInfo(mContext, userInfo);
//            if (((LoginActivity) getActivity()).srequestCode == -1) {
//                getActivity().startActivity(new Intent(mContext, MainTabActivity.class));
//                getActivity().finish();
//            } else {
//                getActivity().setResult(RESULT_OK);
//                getActivity().finish();
//            }
//        }
    }

    @Override
    public void registSuc() {

    }

    @Override
    public void registFail(String msg) {

    }

    @Override
    public void resetSuc() {

    }

    @Override
    public void bindPhone(String openId, String accessToken) {
        BindPhoneActivity.start(getActivity(), openId, accessToken);
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            getCode.setBackgroundResource(R.drawable.bg_login_send_code_a);
            getCode.setTextColor(ContextCompat.getColor(mContext, R.color.themeColor));
            getCode.setEnabled(false);
            getCode.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
//            getCode.setBackgroundResource(R.drawable.bg_login_send_code);
            getCode.setTextColor(ContextCompat.getColor(mContext, R.color.all_orange_color));
            getCode.setEnabled(true);
            getCode.setText("重新获取");
        }
    }

    @Override
    public void initParams(Bundle bundle) {

    }

}
